package com.demo.utils;

import org.apache.logging.log4j.Logger;

import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;

public class EmailUtils {
    private static final Logger log = LogUtils.getLogger();

    private static final String SMTP_HOST = "smtp.qq.com";
    private static final String SMTP_PORT = "587";
    private static final String FROM_EMAIL = "3315608326@qq.com";
    private static final String PASSWORD = "hjvhfyfvztaxchei"; // 推荐使用加密或环境变量
    private static final String TO_EMAIL = "3315608326@qq.com";

    public static void main(String[] args) {
        if (args.length < 1) {
            log.error("请提供 Allure 报告目录路径");
            return;
        }

        String reportDir = args[0];
        log.info("准备发送 Allure 报告: " + reportDir);

        try {
            // 1. 压缩 Allure 报告目录
            File zipFile = File.createTempFile("allure-report", ".zip");
            zipDirectory(new File(reportDir), zipFile);

            // 2. 收集附件（ZIP 文件 + 日志文件）
            List<File> filesToAttach = new ArrayList<>();
            filesToAttach.add(zipFile);

            File logFile = new File(System.getProperty("user.dir") + "/logs/api-test.log");
            if (logFile.exists()) {
                filesToAttach.add(logFile);
            }

            // 3. 邮件内容
            String testResult = "测试总数: 1\n成功: 1\n失败: 0";

            // 4. 发送邮件
            sendTestReportWithAttachments(testResult, filesToAttach);

            // 删除临时文件
            zipFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩目录到 ZIP 文件
     *
     * @param dir     要压缩的目录
     * @param zipFile 输出的 ZIP 文件
     * @throws IOException 如果压缩失败
     */
    private static void zipDirectory(File dir, File zipFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            Path dirPath = dir.toPath();
            Files.walk(dirPath)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(dirPath.relativize(path).toString());
                        try {
                            zos.putNextEntry(zipEntry);
                            Files.copy(path, zos);
                            zos.closeEntry();
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });
        }
    }

    /**
     * 发送带附件的测试报告邮件
     *
     * @param testResult   测试结果
     * @param filesToAttach 附件列表
     */
    public static void sendTestReportWithAttachments(String testResult, List<File> filesToAttach) {
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_EMAIL, PASSWORD);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(TO_EMAIL));
            message.setSubject("API 测试报告 - " + java.time.LocalDate.now());

            // 邮件正文
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(testResult);

            // 多部分内容（正文 + 附件）
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);

            // 添加附件
            for (File file : filesToAttach) {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                attachmentPart.setDataHandler(new DataHandler(source));
                attachmentPart.setFileName(file.getName());
                multipart.addBodyPart(attachmentPart);
            }

            message.setContent(multipart);
            Transport.send(message);

            log.info("测试报告邮件发送成功");

        } catch (Exception e) {
            log.error("邮件发送失败: " + e.getMessage());
        }
    }
}